package com.truonghau.xmeasure.commons;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ParseException;

import com.truonghau.shipper.R;

public class FileUtil {
	public static String getTextFromFileVerification(String fileName,
			Context context) {
		try {
			FileInputStream fIn = context.openFileInput(fileName);
			InputStreamReader isr = new InputStreamReader(fIn);
			/*
			 * Prepare a char-Array that will hold the chars we read back in.
			 */
			char[] inputBuffer = new char[32];
			isr.read(inputBuffer);
			return new String(inputBuffer);
		} catch (Exception e) {
			System.err.println(e.getStackTrace().toString());
			return Constants.ERROR_STRING;
		}
	}

	public static String getTextFromFile(String fileName, Context context) {
		try {
			StringBuilder text = new StringBuilder();
			File f = new File(fileName);
			if (f.exists()) {
				BufferedReader br = new BufferedReader(new FileReader(f));
				String line;

				while ((line = br.readLine()) != null) {
					text.append(line);
					text.append('\n');
				}
			}
			return new String(text);
		} catch (Exception e) {
			System.err.println(e.getStackTrace().toString());
			return Constants.ERROR_STRING;
		}
	}

	public static void alertbox(String title, String mymessage, Context context) {
		new AlertDialog.Builder(context)
		.setMessage(mymessage)
		.setTitle(title)
		.setCancelable(true)
		.setNeutralButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,
					int whichButton) {
			}
		}).show();
	}

	public static void taoFileTXT(String noidung, String fileName,
			Context context) {
		try {
			// catches IOException below
			final String TEXTSTRING = new String(noidung);
			FileOutputStream fOut = context.openFileOutput(fileName,
					Context.MODE_WORLD_WRITEABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fOut);
			// Write the string to the file
			osw.write(TEXTSTRING);
			/*
			 * ensure that everything is really written out and close
			 */
			osw.flush();
			osw.close();
		} catch (Exception ioe) {
			ioe.printStackTrace();
		}
	}

	public static void addLineToFile(String line, String fileName,
			Context context) {

		try {
			// catches IOException below
			String filePath = context.getResources().getString(
					R.string.pathToExportFile);// +fileName;
			File folder = new File(filePath);
			if (!folder.exists()) {
				folder.mkdirs();
			}

			File f = new File(filePath + fileName);
			final String TEXTSTRING = new String(line);
			FileWriter fOut = new FileWriter(f, true);
			// Write the string to the file
			fOut.append(TEXTSTRING);
			fOut.append("\n");
			fOut.flush();
			fOut.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public static void deleteFile(String fileName, Context context) {

		// catches IOException below
		String filePath = context.getResources().getString(
				R.string.pathToExportFile);// +fileName;
		File folder = new File(filePath);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		File f = new File(filePath + fileName);
		if (f.exists()) {
			f.delete();
		}
	}


	public static long getLinesTotal(String fileName, Context context){
		String selectedPath = context.getResources().getString(
				R.string.pathToExportFile)
				+ fileName;
		String noidung = getTextFromFile(selectedPath, context);
		String listLine[];
		if (noidung != null && !Constants.ERROR_STRING.equals(noidung)) {
			listLine = noidung.split("\n");
			return listLine.length;
		}else{
			return 0;
		}
	}

	public static String convertDateToString(Date date) {
		String rt = "";
		if (date != null) {
			try {
				SimpleDateFormat formatter = new SimpleDateFormat(
						Constants.DATE_FORMAT);
				rt = formatter.format(date);
			} catch (ParseException e) {
				System.out.println("Exception :" + e);
			}
		}
		return rt;
	}

	public static Date convertStringToDate(String str) {
		Date rt = null;
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(
					Constants.DATE_FORMAT);
			rt = (Date) formatter.parse(str);
		} catch (Exception e) {
			System.out.println("Exception :" + e);
		}
		return rt;
	}

	public static String getFileName() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd'_'hhmmss");
		return sdf.format(new Date());
	}

	public static String getFileNameFromPath(String path){
		int pos = path.lastIndexOf("/");
		return path.substring(pos+1);
	}



	public static void initFileConfig(Context context) {
		String kttFileName = context.getResources().getString(
				R.string.pathToExportFile)
				+ Constants.FILE_NAME_LIST_KTT;
		String datumFileName = context.getResources().getString(
				R.string.pathToExportFile)
				+ Constants.FILE_NAME_LIST_DATUM;
		String elipsoidFileName = context.getResources().getString(
				R.string.pathToExportFile)
				+ Constants.FILE_NAME_LIST_ELIPSOID;

		// make directory of project xcompass
		String filePathFolder = context.getResources().getString(
				R.string.pathToExportFile);
		File folder = new File(filePathFolder);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		// file kinh tuyen truc
		try {
			File f = new File(kttFileName);
			if (!f.exists()) {
				String noidung = readTxt(context, R.raw.listktt);
				addLineToFile(noidung, Constants.FILE_NAME_LIST_KTT, context);
			}
		} catch (Exception e) {
			alertbox(context.getString(R.string.app_name),
					context.getString(R.string.errFileConfig),
					context);
		}
		// file datum
		try {
			File f = new File(datumFileName);
			if (!f.exists()) {
				String noidung = readTxt(context, R.raw.listdatum);
				addLineToFile(noidung, Constants.FILE_NAME_LIST_DATUM, context);
			}
		} catch (Exception e) {
			alertbox(context.getString(R.string.app_name),
					context.getString(R.string.errFileConfig),
					context);
		}
		// file elipsoid
		try {
			File f = new File(elipsoidFileName);
			if (!f.exists()) {
				String noidung = readTxt(context, R.raw.listelipsoid);
				addLineToFile(noidung, Constants.FILE_NAME_LIST_ELIPSOID,
						context);
			}
		} catch (Exception e) {
			alertbox(context.getString(R.string.app_name),
					context.getString(R.string.errFileConfig),
					context);
		}

	}

	private static String readTxt(Context context, int keyId) {
		InputStream inputStream = context.getResources().openRawResource(keyId);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		int i;
		try {
			i = inputStream.read();
			while (i != -1) {
				byteArrayOutputStream.write(i);
				i = inputStream.read();
			}
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return byteArrayOutputStream.toString();
	}
	private static List<String> getListStrFromFile(String fileName,
			Context context) {
		String noidung = getTextFromFile(fileName, context);
		String listLine[];
		List<String> list = new ArrayList<String>();
		/*
		 * struct of file 
		 */
		if (noidung != null && !Constants.ERROR_STRING.equals(noidung)) {
			listLine = noidung.trim().split("\n");
			for (String line : listLine) {
				list.add(line);
			}
		} else {
			return null;
		}
		return list;
	}
	//export point list to excel
	private static HSSFWorkbook createWB(HSSFWorkbook resultWorkbook, List<String> listHeader, List<String> listObj){
		if(resultWorkbook == null) resultWorkbook = new HSSFWorkbook();
		HSSFSheet sheet = resultWorkbook.createSheet();
		sheet = createExcelHeader(sheet, resultWorkbook, listHeader);
		HSSFRow row = null;
		int rowNum = 0;
		for (String line : listObj) {
			rowNum++;
			row = sheet.createRow(rowNum);
			String listVal[] = line.split(";");
			if(listVal.length == listHeader.size() || listVal.length == listHeader.size() - 1)
				for (int i = 0; i < listVal.length; i++) {
					String string = listVal[i];
					setCellValue(row, i, string == null ? "" : string);
				}

		}
		return  resultWorkbook;
	}
	private static HSSFSheet createExcelHeader(HSSFSheet sheet, HSSFWorkbook resultWorkbook, List<String> listHeader){
		HSSFRichTextString header = null;
		HSSFRow row0 = sheet.createRow(0);
		for (int i = 0; i < listHeader.size(); i++) {
			header = new HSSFRichTextString(listHeader.get(i));
			header.applyFont(HSSFFont.BOLDWEIGHT_BOLD);
			row0.createCell(i).setCellValue(header);
		}
		return sheet;
	}
	private static void setCellValue(HSSFRow row, int colNum, String value) {
		if (value != null) {
			row.createCell(colNum).setCellValue(new HSSFRichTextString(value));
		}
	}
}
